const express = require("express");

const app = express();

const mysql = require("mysql");
var db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "users",
});

db.connect();
let data = [];

// 查询
/* let sql = "select * from books";
db.query(sql, (err, res, fields) => {
  if (err) throw err;
  console.log(res);
  data = res;
}); */

//查询单条数据
/* let sql = "select * from books where id = 1";
db.query(sql, (err, res, fields) => {
  if (err) throw err;
  console.log(res);
  data = res;
}); */

//添加数据
/* let sql = "insert into books (name,author,des) values('三国演义','罗贯中','既生瑜何生亮')"
db.query(sql, (err, res, fields) => {
    if (err) throw err;
    console.log(res);
    data = res;
  }); */

// 删除数据
/* let sql = "delete from books where id = 3"
db.query(sql, (err, res, fields) => {
    if (err) throw err;
    console.log(res);
    data = res;
  }); */

  //改数据 写法一
 /*  let sql = "update books set name='中华上下五千年', author='中华人民',des='一部中华民族的兴衰史' where id =3"
  db.query(sql, (err, res, fields) => {
    if (err) throw err;
    console.log(res);
    data = res;
  }); */

  // 改数据 写法二
  let sql = "update books set name=?, author=?,des=? where id =?"
  db.query(sql, ['浪潮之巅','吴军','it巨头的兴衰史',4], (err, res, fields) => {
    if (err) throw err;
    console.log(res);
    data = res;
  });

db.end();

app.get("/books", (req, res) => {
  res.send(data);
});

app.listen(3000, () => {
  console.log("3000 running");
});
